package com.gsbelarus.gedemin.income.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ListView;

import com.gsbelarus.gedemin.income.adapter.DrawerListAdapter;
import com.gsbelarus.gedemin.income.fragment.CalendarFrgm;
import com.gsbelarus.gedemin.income.fragment.ClientsListFrgm;
import com.gsbelarus.gedemin.income.fragment.ClientsMonthListFrgm;
import com.gsbelarus.gedemin.income.fragment.GraphFrgm;
import com.gsbelarus.gedemin.income.fragment.IncomeFrgm;
import com.gsbelarus.gedemin.income.fragment.SettingsFragment;
import com.gsbelarus.gedemin.income.fragment.ViewPagerDateFrgm;
import com.gsbelarus.gedemin.income.table.DrawerListTable;
import com.gsbelarus.gedemin.income.R;
import com.gsbelarus.gedemin.income.sync.SyncService;
import com.gsbelarus.gedemin.income.fragment.BalanceFrgmVP;
import com.gsbelarus.gedemin.income.interfaces.OnChangeBalanceFragment;
import com.gsbelarus.gedemin.lib.ui.ArgumentsHelper;
import com.gsbelarus.gedemin.lib.ui.NotifHelper;

import java.util.Calendar;

public class Main extends SyncActivity implements OnChangeBalanceFragment {

    public enum DrawerMenuItem {
        BALANCE, INCOME, CLIENTS_MONTH, CLIENTS, CALENDAR, GRAPH, SETTINGS, HELP, EXIT
    }

    private String[] mainNamesDrawerMenu;

    private DrawerLayout mDrawer;
    private ListView mDrawerMenu;
    private DrawerMenuItem lastSelectItem;
    private boolean onClick;
    public static boolean isDrawerOpen = false;

    private Fragment currentFragment;

    @Override
    public int getViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void onFinishUpdateDB() {
        /** закрываем диалог выбора даты, если он открыт */
        if (currentFragment.isAdded()) {
            if (currentFragment instanceof ViewPagerDateFrgm)
                if (((ViewPagerDateFrgm) currentFragment).getDatePickerDialog() != null)
                    ((ViewPagerDateFrgm) currentFragment).getDatePickerDialog().cancel();
            if (currentFragment instanceof BalanceFrgmVP)
                if (((BalanceFrgmVP) currentFragment).getCurrentFragment().getDatePickerDialog() != null)
                    ((BalanceFrgmVP) currentFragment).getCurrentFragment().getDatePickerDialog().cancel();
        }
        /** перерисовываем текущий fragment */
        selectItemMain(lastSelectItem);
        setShowingSyncStatusDialog(true);
    }

    @Override
    public void onCreateActivity(Bundle savedInstanceState) {
        super.onCreateActivity(savedInstanceState);
        mainNamesDrawerMenu = getResources().getStringArray(R.array.drawer_list);
        // Вызовем инициализацию drawer-а
        initDrawer();

        initDrawerMenu();

        /** выставляем id страницы, если активити восстановлена берем из savedInstanceState, иначе BALANCE */
        lastSelectItem = DrawerMenuItem.values()[savedInstanceState.getInt("itemSelected", DrawerMenuItem.BALANCE.ordinal())];
        selectItemMain(lastSelectItem);
    }

    /**
     * Создание, заполнение, назначение слушателя для меню Navigation Drawer-а
     */
    private void initDrawerMenu() {
        mDrawerMenu = (ListView) findViewById(R.id.list_drawer);
        mDrawerMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (mDrawer != null)
                    mDrawer.closeDrawers();
                if (position < mainNamesDrawerMenu.length) {
                    lastSelectItem = DrawerMenuItem.values()[position];
                    onClick = true;
                    /** если mDrawer == null, значит устройство - планшет и дожидаться закрытия mDrawer не нужно*/
                    if (mDrawer == null)
                        selectItemMain(DrawerMenuItem.values()[position]);
                } else
                    selectItemOther(DrawerMenuItem.values()[position]);
            }
        });
        DrawerListAdapter adapter = new DrawerListAdapter(context, mainNamesDrawerMenu.length);
        for (String item : mainNamesDrawerMenu) {
            adapter.add(new DrawerListTable(item, DrawerListAdapter.MAIN_ITEM));
        }
        adapter.add(new DrawerListTable(
                getResources().getDrawable(R.drawable.ic_settings),
                getString(R.string.action_settings), DrawerListAdapter.OTHER_ITEM));
        adapter.add(new DrawerListTable(
                getResources().getDrawable(R.drawable.ic_help),
                getString(R.string.action_help), DrawerListAdapter.OTHER_ITEM));
        adapter.add(new DrawerListTable(
                getResources().getDrawable(R.drawable.ic_exit),
                getString(R.string.action_exit), DrawerListAdapter.OTHER_ITEM));

        mDrawerMenu.setAdapter(adapter);
    }

    /**
     * создание панели NavigationDrawer
     */
    private void initDrawer() {
        mDrawer = (DrawerLayout) findViewById(R.id.drawer);

        // Если drawer не используется (используется планшетный layout)
        if (mDrawer == null)
            return;

        // Создадим drawer toggle для управления индикатором сверху
        setDrawerToggle(new ActionBarDrawerToggle(this, mDrawer,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close) {

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                isDrawerOpen = true;
                getSupportActionBar().setTitle(getString(R.string.app_name));
                supportInvalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                isDrawerOpen = false;
                onChange(lastSelectItem);
                supportInvalidateOptionsMenu();
                if (onClick) {
                    selectItemMain(lastSelectItem);
                    onClick = false;
                }
                super.onDrawerClosed(drawerView);
            }
        });

        // Назначим его drawer-у как слушателя
        mDrawer.setDrawerListener(mDrawerToggle);

        // Добавим тени с той же гравитацией
        mDrawer.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);

        // Включим кнопки на action bar
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    private void selectItemOther(DrawerMenuItem drawerMenuItem) {
        mDrawerMenu.setItemChecked(lastSelectItem.ordinal(), true);
        switch (drawerMenuItem) {
            case SETTINGS:
                Intent settingIntent = new Intent(Main.this, Settings.class);
                startActivity(settingIntent);
                break;
            case HELP:
                Intent helpIntent = new Intent(Main.this, Help.class);
                startActivity(helpIntent);
                break;
            case EXIT:
                /** т.к. после вызова finish() activity не полностью удаляется из памяти,
                 * а значит при следующем запуске есть вероятность восстановления переменной isDrawerOpen,
                 * нужно "обнулять" перемменную.
                 */
                isDrawerOpen = false;
                stopService(new Intent(Main.this, SyncService.class));
                new NotifHelper(context, null).clearNotification();
                finish();
                break;
        }
    }

    private void selectItemMain(DrawerMenuItem drawerMenuItem) {
        onChange(drawerMenuItem);
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        if (currentFragment != null)
            fragmentTransaction.remove(currentFragment);
        switch (drawerMenuItem) {
            case BALANCE:
                currentFragment = new BalanceFrgmVP();
                ((BalanceFrgmVP) currentFragment).setOnChangeBalanceFragment(this);
                break;
            case INCOME:
                currentFragment = new ViewPagerDateFrgm();
                currentFragment.setArguments(ArgumentsHelper.putViewPagerInfo(null, IncomeFrgm.class.getName(), Calendar.DATE));
                break;
            case CLIENTS_MONTH:
                currentFragment = new ViewPagerDateFrgm();
                currentFragment.setArguments(ArgumentsHelper.putViewPagerInfo(null, ClientsMonthListFrgm.class.getName(), Calendar.MONTH));
                break;
            case CLIENTS:
                currentFragment = new ClientsListFrgm();
                break;
            case CALENDAR:
                currentFragment = new ViewPagerDateFrgm();
                currentFragment.setArguments(ArgumentsHelper.putViewPagerInfo(null, CalendarFrgm.class.getName(), Calendar.YEAR));
                break;
            case GRAPH:
                currentFragment = new ViewPagerDateFrgm();
                currentFragment.setArguments(ArgumentsHelper.putViewPagerInfo(null, GraphFrgm.class.getName(), Calendar.YEAR));
                break;
        }
        fragmentTransaction.add(R.id.content, currentFragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * Вызывается при свайпах из экрана Расчетный счет
     */
    @Override
    public void onChange(DrawerMenuItem drawerMenuItem) {
        if (mDrawer != null)
            mDrawer.closeDrawers();
        lastSelectItem = drawerMenuItem;
        mDrawerMenu.setItemChecked(drawerMenuItem.ordinal(), true);
        getSupportActionBar().setTitle(mainNamesDrawerMenu[drawerMenuItem.ordinal()]);
    }

    /**
     * фикс для https://code.google.com/p/android/issues/detail?id=29472
     */
    @Override
    public void supportInvalidateOptionsMenu() {
        ViewPager mViewPager = null;
        if (currentFragment != null) {
            if (currentFragment instanceof ViewPagerDateFrgm)
                mViewPager = ((ViewPagerDateFrgm) currentFragment).getViewPager();
            else if (currentFragment instanceof BalanceFrgmVP)
                mViewPager = ((BalanceFrgmVP) currentFragment).getViewPager();
        }
        if (mViewPager != null)
            mViewPager.post(new Runnable() {
                @Override
                public void run() {
                    Main.super.supportInvalidateOptionsMenu();
                }
            });
        else
            Main.super.supportInvalidateOptionsMenu();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (isDrawerOpen) {
            return false;
        } else
            return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("itemSelected", lastSelectItem.ordinal());

        /** убираем сохраненный системой фрагмент */
        outState.remove("android:support:fragments");
    }

    @Override
    protected void onResume() {
        super.onResume();
        /* Если первый запуск показываем диалоговое окно и создаем демо данные */
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        if (pref.getBoolean("firstrun", true) && !pref.getBoolean(SettingsFragment.WORK_MODE, false)) {

            startService(new Intent(this, SyncService.class));

        }
        pref.edit().putBoolean("firstrun", false).commit();
    }
}
